package com.jt.controller;

import com.jt.annotation.RequiredLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;


@Slf4j
@RestController
@RefreshScope
@RequestMapping("/resource")
public class ResourceController {
    @Value("${jt.resource.path}")
    private String resourcePath;
    @Value("${jt.resource.host}")
    private String resourceHost;

    @RequiredLog("文件上传")
    @PostMapping("/upload")
    public String uploadFile(MultipartFile uploadFile) throws IOException {
        //1.创建文件存储目录（按照时间创建）
        //1.1获取当前时间的一个目录
        String dateDir = 
                DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
        //1.2创建目录文件对象
        File uploadFileDir = new File(resourcePath,dateDir);
        if(!uploadFileDir.exists())uploadFileDir.mkdirs();
        //2 获取原文件后缀
        //2.1获取原始文件名
        String originalFilename = uploadFile.getOriginalFilename();
        String fileSuffix = originalFilename.substring(
                originalFilename.lastIndexOf("."));
        //构建新的文件名字
        String newFilePrefix = UUID.randomUUID().toString();
        String newFileName = newFilePrefix+fileSuffix;
        File file = new File(uploadFileDir, newFileName);
        uploadFile.transferTo(file);
        String fileRealPath = resourceHost+dateDir+"/"+newFileName;
        log.debug("fileRealPath {}",fileRealPath);
        return  fileRealPath;
    }

}
